﻿using ET.DBCommon.DAL;
using ET.DBCommon.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// SequenceDiagramView.xaml 的交互逻辑
    /// </summary>
    public partial class SequenceDiagramView : Window
    { 
        /// <summary>
        /// 时序图窗体 add by zzg
        /// </summary>
        /// <param name="ExamresultsStepID"></param>
        public SequenceDiagramView(int ExamresultsStepID,string name)
        {
            InitializeComponent();
            ExamresultsStepID = ExamresultsStepID;
            GenerateName = name + "_" + ExamresultsStepID;
        }
        //图片名称
        string GenerateName;
        int ExamresultsStepID { get; set; }
        private int QuestionID { get; set; }
        public string[] StopsRunningTrain { get; set; }
        //有说话的地方了
        double TimeH = 30;
        //说一句话的高度
        double QuantityH = 35;
        //字体高度
        double FontH = 25;
        //边距距离
        double Magin = 10;
        //上边距距离
        double MaginT = 30;
        //对象控件宽度
        double objectW = 30;
        //左边距距离
        double MaginL = 60;
        //根据数据计算行调的长度
        double DiaoDuH = 0;
        private SolidColorBrush NonLineBrush = new SolidColorBrush(Color.FromRgb(0, 204, 0));
        private SolidColorBrush SolidLineBrush = Brushes.Red;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //获取数据
            // var sequencediagramlist = SequenceDiagramDAL.GetSequenceDiagram(ExamresultsStepID);
            var sequencediagramlist = SequenceDiagramDAL.GetSequenceDiagram(10);
            if (sequencediagramlist == null) return;
            List<umlSequenceDiagram> umlSequencelist = new List<umlSequenceDiagram>();
            //整理数据

            umlSequenceDiagram umlSequence = new umlSequenceDiagram();
            for (int i = 0; i < sequencediagramlist.Count; i++)
            {
                umlSequence.ID = i;
                umlSequence.ExamresultsStepID = sequencediagramlist[i].ExamresultsStepID;
                umlSequence.DeviceID = sequencediagramlist[i].DeviceID;
                umlSequence.DeviceTypeID = sequencediagramlist[i].DeviceTypeID;
                umlSequence.SystemType = sequencediagramlist[i].SystemType.ToString ();
              
                umlSequence.IsMain = sequencediagramlist[i].IsMain;
                Umldetails umldetailslist = new Umldetails();
                umldetailslist.OperID = sequencediagramlist[i].OperID;
                umldetailslist.Parameters = sequencediagramlist[i].Parameters;
                umlSequence.umldetails.Add(umldetailslist);
                if (i < sequencediagramlist.Count - 1)
                {
                    if (umlSequence.DeviceID != sequencediagramlist[i + 1].DeviceID)
                    {
                        umlSequencelist.Add(umlSequence);
                        umlSequence = new umlSequenceDiagram();
                    }
                    else if (umlSequence.IsMain!= sequencediagramlist[i + 1].IsMain)
                    {
                        umlSequencelist.Add(umlSequence);
                        umlSequence = new umlSequenceDiagram();
                    }
                }
                else
                {
                    umlSequencelist.Add(umlSequence);
                    umlSequence = new umlSequenceDiagram();
                }
            }

            DiaoDuH = sequencediagramlist.Count * 35 + umlSequencelist.Count*30+100;
            //获取宽度
            double width = this.ActualWidth;
            grid.Width = (width) * 0.75;
            if ((width) * 0.75 < 500)
                grid.Width = 1200;

            grid.Height = DiaoDuH+100;
            diagramCanvas.Width = grid.Width;
            diagramCanvas.Height = grid.Height;
            //多出的长度
            double ExtraH = 100;
            double SetLeft = grid.Width / 10;
            //ATS水平距离
            double ATSW = SetLeft * 7;
            //驾驶员水平距离
            double DriverW = SetLeft * 3;
            //值班员距离
            double DutyW = SetLeft * 5;
            //调度员距离
            double DispatchW = SetLeft;
            //上级部门离
            double SuperiorW = SetLeft * 9;

            Line DottedLE = new Line();
            #region 五条虚线
            for (int i = 0; i < 5; i++)
            {
                //虚线
                DottedLE = new Line()
                {
                    Stroke = Brushes.Black,
                    X1 = SetLeft * (i + i + 1),
                    X2 = SetLeft * (i + i + 1),
                    Y1 = 0,
                    Y2 = DiaoDuH + ExtraH,
                    StrokeDashArray = new DoubleCollection() { 3, 5 }
                };
                uMLCanvas.Children.Add(DottedLE);
            }
            #endregion
            //实线
            Line SolidLES = new Line();
            //箭头
            Line ArrowLES = new Line();
            TextBlock textBlock = new TextBlock();

            Rectangle rectangle = new Rectangle() { Width = objectW, Height = DiaoDuH, RadiusX = 3, RadiusY = 3, Stroke = Brushes.Red, StrokeThickness = 1, Fill = Brushes.White, };
            //调度
            uMLCanvas.Children.Add(rectangle);
            Canvas.SetTop(rectangle, MaginT);
            Canvas.SetLeft(rectangle, SetLeft - objectW / 2);
            for (int i = 0; i < umlSequencelist.Count; i++)
            {
                SolidColorBrush LineBrush = umlSequencelist[i].IsMain == false ? NonLineBrush : SolidLineBrush;
                switch (umlSequencelist[i].DeviceTypeID)
                {
                    //无线电台
                    case 8:
                        rectangle = new Rectangle() { Width = objectW, Height = QuantityH * umlSequencelist[i].umldetails.Count + (Magin * 2), RadiusX = 3, RadiusY = 3, Stroke = Brushes.Red, StrokeThickness = 1, Fill = Brushes.White, };

                        uMLCanvas.Children.Add(rectangle);
                        TimeH += MaginT;
                        Canvas.SetTop(rectangle, TimeH);
                        Canvas.SetLeft(rectangle, DriverW - (objectW / 2));
                        for (int k = 0; k < umlSequencelist[i].umldetails.Count; k++)
                        {
                            TimeH = TimeH + QuantityH;
                            if (umlSequencelist[i].umldetails[k].OperID == 95)//虚线
                            {
                                //虚线
                                SolidLES = new Line()
                                {
                                    Stroke = LineBrush,
                                    X1 = DriverW - (objectW),
                                    X2 = DispatchW + (objectW),
                                    Y1 = TimeH,
                                    Y2 = TimeH,
                                    StrokeThickness = 2,
                                    StrokeDashArray = new DoubleCollection() { 3, 5 }
                                };
                                ArrowLES = new Line()
                                {
                                    Stroke = LineBrush,
                                    X1 = DispatchW + (objectW) + 5,
                                    X2 = DispatchW + (objectW) + 4,
                                    Y1 = TimeH,
                                    Y2 = TimeH,
                                    StrokeThickness = 12,
                                    StrokeEndLineCap = PenLineCap.Triangle
                                };
                            }
                            else//实线
                            {
                                //实线
                                SolidLES = new Line()
                                {
                                    Stroke = LineBrush,
                                    X1 = DispatchW + (objectW),
                                    X2 = DriverW - objectW,
                                    Y1 = TimeH,
                                    Y2 = TimeH,
                                    StrokeThickness = 2
                                };
                                ArrowLES = new Line()
                                {
                                    Stroke = LineBrush,
                                    X1 = DriverW - objectW,
                                    X2 = DriverW - objectW + 1,
                                    Y1 = TimeH,
                                    Y2 = TimeH,
                                    StrokeThickness = 12,
                                    StrokeEndLineCap = PenLineCap.Triangle
                                };
                            }
                            uMLCanvas.Children.Add(SolidLES);
                            uMLCanvas.Children.Add(ArrowLES);
                            textBlock = new TextBlock { Width = (DriverW - DispatchW) - MaginL, TextTrimming = TextTrimming.CharacterEllipsis, FontSize = 16, };
                            textBlock.Text = umlSequencelist[i].umldetails[k].Parameters;
                            textBlock.ToolTip = umlSequencelist[i].umldetails[k].Parameters;
                            uMLCanvas.Children.Add(textBlock);
                            Canvas.SetTop(textBlock, TimeH - FontH);
                            Canvas.SetLeft(textBlock, DispatchW + objectW + Magin);

                        }
                        break;
                    //调度电话
                    case 5:
                        rectangle = new Rectangle() { Width = objectW, Height = QuantityH * umlSequencelist[i].umldetails.Count + (Magin * 2), RadiusX = 3, RadiusY = 3, Stroke = Brushes.Red, StrokeThickness = 1, Fill = Brushes.White, };

                        uMLCanvas.Children.Add(rectangle);
                        TimeH += MaginT;
                        if (umlSequencelist[i].DeviceID == "27")//上级领导
                        {
                            Canvas.SetTop(rectangle, TimeH);
                            Canvas.SetLeft(rectangle, SuperiorW - (objectW / 2));
                            for (int k = 0; k < umlSequencelist[i].umldetails.Count; k++)
                            {
                                TimeH = TimeH + QuantityH;
                                if (umlSequencelist[i].umldetails[k].OperID == 91)//虚线
                                {
                                    //虚线
                                    SolidLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = SuperiorW - (objectW),
                                        X2 = DispatchW + (objectW),
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 2,
                                        StrokeDashArray = new DoubleCollection() { 3, 5 }
                                    };
                                    ArrowLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = DispatchW + (objectW) + 5,
                                        X2 = DispatchW + (objectW) + 4,
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 12,
                                        StrokeEndLineCap = PenLineCap.Triangle
                                    };
                                }
                                else
                                {
                                    //实线
                                    SolidLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = DispatchW + (objectW),
                                        X2 = SuperiorW - objectW,
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 2
                                    };
                                    ArrowLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = SuperiorW - objectW,
                                        X2 = SuperiorW - objectW + 1,
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 12,
                                        StrokeEndLineCap = PenLineCap.Triangle
                                    };
                                }
                                uMLCanvas.Children.Add(SolidLES);
                                uMLCanvas.Children.Add(ArrowLES);
                                textBlock = new TextBlock { Width = (SuperiorW - DispatchW) - Magin, TextTrimming = TextTrimming.CharacterEllipsis, FontSize = 16, };
                                textBlock.Text = umlSequencelist[i].umldetails[k].Parameters;
                                textBlock.ToolTip = umlSequencelist[i].umldetails[k].Parameters;
                                uMLCanvas.Children.Add(textBlock);
                                Canvas.SetTop(textBlock, TimeH - FontH);
                                Canvas.SetLeft(textBlock, DispatchW + objectW + Magin);
                            }
                        }
                        else //站台
                        {
                            Canvas.SetTop(rectangle, TimeH);
                            Canvas.SetLeft(rectangle, DutyW - (objectW / 2));
                            for (int k = 0; k < umlSequencelist[i].umldetails.Count; k++)
                            {
                                TimeH = TimeH + QuantityH;
                                if (umlSequencelist[i].umldetails[k].OperID == 91)//虚线
                                {
                                    //虚线
                                    SolidLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = DutyW - (objectW),
                                        X2 = DispatchW + (objectW),
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 2,
                                        StrokeDashArray = new DoubleCollection() { 3, 5 }
                                    };
                                    ArrowLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = DispatchW + (objectW) + 5,
                                        X2 = DispatchW + (objectW) + 4,
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 12,
                                        StrokeEndLineCap = PenLineCap.Triangle
                                    };

                                }
                                else
                                {
                                    //实线
                                    SolidLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = DispatchW + (objectW),
                                        X2 = DutyW - objectW,
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 2
                                    };
                                    ArrowLES = new Line()
                                    {
                                        Stroke = LineBrush,
                                        X1 = DutyW - objectW,
                                        X2 = DutyW - objectW + 1,
                                        Y1 = TimeH,
                                        Y2 = TimeH,
                                        StrokeThickness = 12,
                                        StrokeEndLineCap = PenLineCap.Triangle
                                    };
                                }
                                uMLCanvas.Children.Add(SolidLES);
                                uMLCanvas.Children.Add(ArrowLES);

                                textBlock = new TextBlock { Width = (DutyW - DispatchW) - MaginL, TextTrimming = TextTrimming.CharacterEllipsis, FontSize = 16, };
                                textBlock.Text = umlSequencelist[i].umldetails[k].Parameters;
                                textBlock.ToolTip = umlSequencelist[i].umldetails[k].Parameters;
                                uMLCanvas.Children.Add(textBlock);
                                Canvas.SetTop(textBlock, TimeH - FontH);
                                Canvas.SetLeft(textBlock, DispatchW + objectW + Magin);
                            }
                        }
                        break;
                    //ATS操作端
                    case 6:
                        rectangle = new Rectangle() { Width = objectW, Height = QuantityH * umlSequencelist[i].umldetails.Count + (Magin * 2), RadiusX = 3, RadiusY = 3, Stroke = Brushes.Red, StrokeThickness = 1, Fill = Brushes.White, };

                        uMLCanvas.Children.Add(rectangle);
                        TimeH += MaginT;
                        Canvas.SetTop(rectangle, TimeH);
                        Canvas.SetLeft(rectangle, ATSW - (objectW / 2));
                        for (int k = 0; k < umlSequencelist[i].umldetails.Count; k++)
                        {
                            TimeH = TimeH + QuantityH;
                            SolidLES = new Line()
                            {
                                Stroke = LineBrush,
                                X1 = DispatchW + (objectW),
                                X2 = ATSW - objectW,
                                Y1 = TimeH,
                                Y2 = TimeH,
                                StrokeThickness = 2
                            };
                            ArrowLES = new Line()
                            {
                                Stroke = LineBrush,
                                X1 = ATSW - objectW,
                                X2 = ATSW - objectW + 1,
                                Y1 = TimeH,
                                Y2 = TimeH,
                                StrokeThickness = 12,
                                StrokeEndLineCap = PenLineCap.Triangle
                            };
                            uMLCanvas.Children.Add(SolidLES);
                            uMLCanvas.Children.Add(ArrowLES);
                            // 说的话
                            textBlock = new TextBlock { Width = ATSW - DispatchW - MaginL, TextTrimming = TextTrimming.CharacterEllipsis, FontSize = 16, };
                            textBlock.Text = umlSequencelist[i].umldetails[k].Parameters;
                            textBlock.ToolTip = umlSequencelist[i].umldetails[k].Parameters;
                            uMLCanvas.Children.Add(textBlock);
                            Canvas.SetTop(textBlock, TimeH - FontH);
                            Canvas.SetLeft(textBlock, DispatchW + objectW + Magin);
                        }
                        break;
                }
            }
          
            //晚点
            this.latedataGrid.ItemsSource = TrainLateDAL.GetTrainLateList(this.QuestionID);
            //迫停
            this.trainSuspendGrid.ItemsSource = TrainSuspendDAL.GetTrainSuspendList(this.QuestionID);
            //停运
            this.shutDownsDataGrid.ItemsSource = this.StopsRunningTrain; 
        }

        private void DockPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();

        }
        private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }
        private void WindowMin_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void WindowClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void WindowMax_Click(object sender, RoutedEventArgs e)
        {

        }
        private void Generate_Click(object sender, RoutedEventArgs e)
        {
            string path = GetOpenFilesPath();
            if (path == "")
                return;
            path += @"\"+ GenerateName+".png";
            ExportToPng(path, diagramCanvas);
        }
        /// <summary>
        /// 获取要保存文件名称（含完整路径）
        /// </summary>
        /// <returns></returns>
        private string GetOpenFilesPath()
        {
            string filePath = null;
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.Cancel)
                return filePath;
            filePath = dialog.SelectedPath.Trim();
            return filePath;
        }
        /// <summary>
        /// Canvas转换成图片
        /// </summary>
        /// <param name="path">保存的路径</param>
        /// <param name="surface"> 控件名称</param>
        public void ExportToPng(string path, Canvas surface)
        {
            try
            {
                if (path == null) return;

                Transform transform = surface.LayoutTransform;
                surface.LayoutTransform = null;

                Size size = new Size(surface.Width, surface.Height);
                surface.Measure(size);
                surface.Arrange(new Rect(size));

                RenderTargetBitmap renderBitmap =
                new RenderTargetBitmap(
                (int)size.Width,
                (int)size.Height,
                96d,
                96d,
                PixelFormats.Pbgra32);
                renderBitmap.Render(surface);

                using (FileStream outStream = new FileStream(path, FileMode.Create))
                {
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                    encoder.Save(outStream);
                }
                surface.LayoutTransform = transform;
                MessageBox.Show("图片已生成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
    public class umlSequenceDiagram
    {
        /// <summary>
        /// 操作ID
        /// </summary>
        public int ID { get; set; }
       
        /// <summary>
        /// 操作的设备类型ID,例如：信号机；道岔；进路等
        /// </summary>
        public int DeviceTypeID { get; set; }
        /// <summary>
        /// 操作的设备ID,例如信号机X201的ID
        /// </summary>
        public string DeviceID { get; set; }
        /// <summary>
        /// 1/信号;2/调度电话;3/无线电台
        /// </summary>
        public string  SystemType { get; set; }
     
        /// <summary>
        /// 步骤ID
        /// </summary>
        public int ExamresultsStepID { get; set; }
        /// <summary>
        /// 是否主场景
        /// </summary>
        public bool IsMain { get; set; }
        /// <summary>
        /// 详情
        /// </summary>
        public List<Umldetails> umldetails { get; set; } = new List<Umldetails>();
    }
    public class Umldetails
    {
        /// <summary>
        /// 操作步骤ID
        /// 信号-办理进路
        /// 调度电话-接听
        /// 无线电台-挂断
        /// </summary>
        public int OperID { get; set; }

        /// <summary>
        /// 操作的参数ID,例如
        /// </summary>
        public String Parameters { get; set; }
    }
}
